package com.lmf.serviceUcenter.controller;


import com.lmf.handler.Exception.LmfException;
import com.lmf.resultCode.JwtUtils;
import com.lmf.resultCode.R;
import com.lmf.serviceUcenter.entity.UcenterMember;
import com.lmf.serviceUcenter.entity.vo.RegisterVo;
import com.lmf.serviceUcenter.entity.vo.UcenterQuery;
import com.lmf.serviceUcenter.service.UcenterMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author lmf
 * @since 2022-02-09
 */
@Api(description = "新建用户微服务")
@CrossOrigin
@RestController
@RequestMapping("/serviceUcenter/ucenter-member")
public class UcenterMemberController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    @ApiOperation("用户登录方法")
    @PostMapping("/login")
    public R loginUser(@RequestBody UcenterQuery ucenterQuery) throws LmfException {
        String token = ucenterMemberService.loginAccount(ucenterQuery);
        return R.ok().data("token",token);
    }

    @ApiOperation("用户注册方法")
    @PostMapping("/register")
    public R registerUser(@RequestBody RegisterVo registerVo) throws LmfException {
        ucenterMemberService.registerAccount(registerVo);
        return R.ok().message("注册成功");
    }

    @ApiOperation("根据token获取用户信息")
    @GetMapping("/getUserInfoForJwt")
    public R getUserInfoForJwt(HttpServletRequest request) throws LmfException {
        //从token中解析出用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //再根据id从数据库中查询出用户对象信息
        UcenterMember ucenterMember = ucenterMemberService.getById(memberId);
        //判断非空
        if (ucenterMember != null) {
            //最后返回给前台
            return R.ok().data("userInfo",ucenterMember);
        }else {
            throw new LmfException(20001,"用户不存在");
        }

    }
}

